<template>
  <el-dialog
    v-model="state.dialogVisible"
    :append-to-body="true"
    :before-close="close"
    class="dialog-container"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    top="5vh"
    :modal="model"
    :title="state.dialogTitle"
    :width="width"
  >
    <div style="padding: 0px; overflow: auto">
      <VueJsonPretty
        v-model:data="state.content"
        :deep="3"
        editable
        showLength
        showLineNumber
        virtual
        style="border: 1px solid #606266; height: 400px"
      />
    </div>
    <template #footer>
      <el-button icon="circle-close" type="warning" @click="close">
        取消
      </el-button>
    </template>
  </el-dialog>
</template>
<script setup name="JsonViewer">
import VueJsonPretty from "vue-json-pretty";
import "vue-json-pretty/lib/styles.css";

const props = defineProps({
  title: {
    type: String,
    default: "浏览"
  },
  width: {
    type: String,
    default: "40%"
  },
  model: {
    type: Boolean,
    default: true
  }
});

const state = reactive({
  dialogTitle: props.title,
  dialogVisible: false,
  content: null
});

const show = content => {
  load(content);
  state.dialogVisible = true;
};

const load = content => {
  nextTick(() => {
    try {
      state.content = JSON.parse(content);
    } catch (err) {
      state.content = JSON.parse("{ error: '解析错误,不是JSON数据' }");
    }
  });
};

const close = () => {
  state.dialogVisible = false;
};

defineExpose({
  show,
  close
});
</script>
<style lang="scss" scoped>
.dialog-container {
  min-height: 360px !important;
  max-height: 520px !important;
  overflow: auto;
}
</style>
